﻿using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;
using System;
using System.Data.Entity.SqlServer;
using System.Linq;

namespace Pay.Service {
    public class MerchantBankCardService : ServiceBase, IMerchantBankCardService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        private ISettingService _iSettingService;
        private IMerchantService _merchantService;
        public MerchantBankCardService(IUnitOfWork iUnitOfWork, ISettingService iSettingService, IMerchantService merchantService) : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
            _iSettingService = iSettingService;
            _merchantService = merchantService;
        }

        #region 后台管理
        /// <summary>
        /// 获得银行卡列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedResult<merchant_bank_card_dto> GetBankCards(MerchantBankCardQuery query) {
            var filter = PredicateBuilder.True<MerchantBankCard>();
            if (!string.IsNullOrEmpty(query.nick_name)) {
                filter = filter.And(c => c.Merchant.Name == query.nick_name || c.Merchant.Mobile == query.nick_name);
            }
            if (!string.IsNullOrEmpty(query.account_name)) {
                filter = filter.And(c => c.AccountName == query.account_name);
            }
            if (!string.IsNullOrEmpty(query.status)) {
                int value = int.Parse(query.status);
                filter = filter.And(c => c.Status == (EMerchantBankCardStatus)value);
            }
            if (!string.IsNullOrEmpty(query.begin_time)) {
                DateTime time = DateTime.Parse(query.begin_time);
                filter = filter.And(c => c.UpdateTime >= time);
            }
            if (!string.IsNullOrEmpty(query.end_time)) {
                DateTime time = DateTime.Parse(query.end_time).AddDays(1);
                filter = filter.And(c => c.UpdateTime <= time);
            }
            var result = context.MerchantBankCard.FromCachePaged<MerchantBankCard, merchant_bank_card_dto>(query.page, query.size, filter, orderBy => orderBy.OrderBy(o => SqlFunctions.CharIndex(((int)o.Status).ToString(), "1,2,4,3")).ThenByDescending(o => o.UpdateTime));
            return result;
        }

        /// <summary>
        /// 通过Id获得银行卡
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public merchant_bank_card_dto_ex GetBankCard(long id) {
            return context.MerchantBankCard.Where(o => o.Id == id).FirstOrDefault().ToDtoObject<merchant_bank_card_dto_ex>();
        }

        /// <summary>
        /// 审核银行卡
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="manageId"></param>
        /// <returns></returns>
        public bool AuditBankCard(merchant_bank_card_dto dto, long manageId) {
            var bankCard = context.MerchantBankCard.FindById(dto.id);
            bankCard.Status = dto.status;
            bankCard.AuditUserId = manageId;
            bankCard.AuditTime = DateTime.Now;
            return _iUnitOfWork.Commit() > 0;
        }
        #endregion

        /// <summary>
        /// 获得商户审核通过的银行卡（包括自动审核通过和审核通过的）
        /// </summary>
        /// <param name="merchantId"></param>
        /// <returns></returns>
        public api_merchant_bank_card_dto GetApprovedBankCard(long merchantId) {
            return context.MerchantBankCard.Where(o => o.MerchantId == merchantId &&
            (o.Status == EMerchantBankCardStatus.AutoApproved || o.Status == EMerchantBankCardStatus.Approved)).FromCacheFirstOrDefault<MerchantBankCard, api_merchant_bank_card_dto>();
        }

        /// <summary>
        /// 通过Id获得银行卡
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public api_merchant_bank_card_dto GetBankCardById(long id) {
            return context.MerchantBankCard.Where(o => o.Id == id).FromCacheFirstOrDefault<MerchantBankCard, api_merchant_bank_card_dto>();
        }

        /// <summary>
        /// 通过商户Id获得银行卡
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public api_merchant_bank_card_dto GetBankCardByMerchantId(long merchantId) {
            return context.MerchantBankCard.Where(o => o.MerchantId == merchantId).FromCacheFirstOrDefault<MerchantBankCard, api_merchant_bank_card_dto>();
        }

        /// <summary>
        /// 新增或修改银行卡
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="merchantId"></param>
        /// <returns></returns>
        public bool AddOrUpdateBankCard(edit_merchant_bank_card_dto dto, long merchantId) {
            var merchant = _merchantService.Get(merchantId);
            _iSettingService.ValidCode(merchant.mobile,dto.v_code, "token_bank");
            var token_base_setting = _iSettingService.GetTokenSetting().token_base_setting;
            string authName = string.Empty;//实名姓名
            var authInfo = _merchantService.GetAuth(merchantId); //context.AuthInfos.Where(o => o.MerchantId == merchantId && o.Status == CertifyStatus.Auth).FirstOrDefault();
            if (authInfo != null) {
                authName = authInfo.account_name;
            }
            if (authName != dto.account_name)
                throw new ServerErrorException("银行卡户名必须与实名姓名相同");
            if (dto.id == 0) {//新增
                if (context.MerchantBankCard.Exist(o => o.MerchantId == merchantId))
                    throw new ServerErrorException("您已绑定过银行卡，可进行修改或删除操作");
                var merchant_bank_card_dto = new merchant_bank_card_dto();
                dto.ToCopyProperty(merchant_bank_card_dto);
                MerchantBankCard model = merchant_bank_card_dto.ToDtoObject<MerchantBankCard>();
                model.MerchantId = merchantId;
                model.Status = EMerchantBankCardStatus.Approved;
                //if (token_base_setting.is_bankcard_autoaudit)
                //    model.Status = EMerchantBankCardStatus.AutoApproved;
                //else
                //    model.Status = EMerchantBankCardStatus.ToAudit;

                model.CreateTime = DateTime.Now;
                model.UpdateTime = DateTime.Now;

                context.MerchantBankCard.Add(model);
            } else {
                var model = context.MerchantBankCard.FirstOrDefault(o => o.Id == dto.id && o.MerchantId == merchantId);
                model.AccountName = dto.account_name;
                model.AccountNum = dto.account_num;
                model.BankName = dto.bank_name;
                model.BranchName = dto.branch_name;
                model.HandIdCardImg = dto.hand_id_card_img;
                model.Status = EMerchantBankCardStatus.Approved;

                //if (token_base_setting.is_bankcard_autoaudit)
                //    model.Status = EMerchantBankCardStatus.AutoApproved;
                //else
                //    model.Status = EMerchantBankCardStatus.ToAudit;

                model.UpdateTime = DateTime.Now;
            }
            return _iUnitOfWork.Commit() > 0;

        }

        /// <summary>
        /// 删除银行卡
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool RemoveBankCard(long id) {
            var model = context.MerchantBankCard.FindById(id);
            context.MerchantBankCard.Remove(model);
            return _iUnitOfWork.Commit() > 0;
        }

    }
}
